package com.kadron.comment;

import java.io.Serializable;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.kadron.common.KConst;
import com.kadron.creator.KCommentModelCreator;
import com.kadron.dao.KCommentDAO;
import com.kadron.dao.KImageDAO;
import com.kadron.dao.KUserImageDAO;
import com.kadron.datamodel.KCommentAdminDataProvider;
import com.kadron.datamodel.KDataModel;
import com.kadron.entity.Comment;
import com.kadron.entity.User;
import com.kadron.item.AbstractItemManager;
import com.kadron.session.KUser;

@AutoCreate
@Scope(ScopeType.PAGE)
@Name("kCommentListManager")
public class KCommentListManager extends AbstractItemManager implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3111988099407754250L;
	
	private KDataModel commentList;
	private KCommentAdminDataProvider dataProvider;
	
	@In
	private KUserImageDAO userImageDAO;
	@In
	private KImageDAO imageDAO;
	@In
	private KCommentDAO commentDAO;
	
	@Create
	public void init() {
		try {			
			loadComments();
		} catch (Exception e) {
			super.setError(true);
		}
	}
	
	private void loadComments() {
		dataProvider = new KCommentAdminDataProvider(new KCommentModelCreator(userImageDAO,imageDAO, commentDAO), commentDAO);
		commentList = new KDataModel(dataProvider);
	}

	public KDataModel getCommentList() {
		return commentList;
	}
	
	public void approve(Long commentId) {
		try {		
			User user = KUser.instance().getUser();
			if (user == null) {
				bad(KConst.MUST_LOGIN);
				return;
			}
			if (commentId == null || commentId <= 0) {
				bad(KConst.BAD_THING);
				return;
			}
			Comment comm = commentDAO.find(commentId, Comment.class);
			if (comm == null) {
				bad(KConst.BAD_THING);
				return;
			}
			comm.setApproved(!comm.isApproved());
			comm.setApprovedBy(KUser.instance().getUser().getId());
			comm = (Comment) commentDAO.update(comm);
			good();
		} catch (Exception e) {
			e.printStackTrace();
			bad(KConst.BAD_THING);
		}
	}
}
